from pydantic import BaseModel, Field, validator
from datetime import datetime
from typing import List, Optional, Dict, Any


class RoleBase(BaseModel):
    """角色基础模型"""
    name: str = Field(..., min_length=1, max_length=50, description="角色名称")
    code: str = Field(..., min_length=1, max_length=50, description="角色编码")
    description: Optional[str] = Field(None, description="角色描述")
    permissions: List[str] = Field(default=[], description="权限编码列表")
    sort_order: int = Field(default=0, description="排序")
    is_active: bool = Field(default=True, description="是否激活")
    remark: Optional[str] = Field(None, description="备注")

    @validator('code')
    def validate_code(cls, v):
        """验证角色编码格式"""
        if not v.replace('_', '').replace('-', '').isalnum():
            raise ValueError('角色编码只能包含字母、数字、下划线和连字符')
        return v


class RoleCreateInput(RoleBase):
    """角色创建输入模型"""
    pass


class RoleUpdate(BaseModel):
    """角色更新模型"""
    name: Optional[str] = Field(None, min_length=1, max_length=50, description="角色名称")
    code: Optional[str] = Field(None, min_length=1, max_length=50, description="角色编码")
    description: Optional[str] = Field(None, description="角色描述")
    permissions: Optional[List[str]] = Field(None, description="权限编码列表")
    sort_order: Optional[int] = Field(None, description="排序")
    is_active: Optional[bool] = Field(None, description="是否激活")
    remark: Optional[str] = Field(None, description="备注")

    @validator('code')
    def validate_code(cls, v):
        """验证角色编码格式"""
        if v is not None and not v.replace('_', '').replace('-', '').isalnum():
            raise ValueError('角色编码只能包含字母、数字、下划线和连字符')
        return v


class RoleInfo(BaseModel):
    """角色信息模型"""
    id: int = Field(description="角色ID")
    name: str = Field(description="角色名称")
    code: str = Field(description="角色编码")
    description: Optional[str] = Field(None, description="角色描述")
    permissions: List[str] = Field(description="权限编码列表")
    sort_order: int = Field(description="排序")
    is_active: bool = Field(description="是否激活")
    is_system: bool = Field(description="是否系统角色")
    remark: Optional[str] = Field(None, description="备注")
    created_at: datetime = Field(description="创建时间")
    updated_at: datetime = Field(description="更新时间")

    class Config:
        from_attributes = True


class RoleDetailInfo(BaseModel):
    """角色详细信息模型（包含权限对象）"""
    id: int = Field(description="角色ID")
    name: str = Field(description="角色名称")
    code: str = Field(description="角色编码")
    description: Optional[str] = Field(None, description="角色描述")
    permissions: List[str] = Field(description="权限编码列表")
    permission_objects: List[Dict[str, Any]] = Field(description="权限对象列表")
    sort_order: int = Field(description="排序")
    is_active: bool = Field(description="是否激活")
    is_system: bool = Field(description="是否系统角色")
    remark: Optional[str] = Field(None, description="备注")
    created_at: datetime = Field(description="创建时间")
    updated_at: datetime = Field(description="更新时间")


class RoleListResponse(BaseModel):
    """角色列表响应模型"""
    total: int = Field(description="总数")
    items: List[RoleInfo] = Field(description="角色列表")


class RoleCreatedResponse(BaseModel):
    """角色创建成功响应模型"""
    id: int = Field(description="角色ID")
    name: str = Field(description="角色名称")
    code: str = Field(description="角色编码")


class RolePermissionUpdate(BaseModel):
    """角色权限更新模型"""
    permissions: List[str] = Field(..., description="权限编码列表")


class RoleBatchUpdate(BaseModel):
    """角色批量更新模型"""
    ids: List[int] = Field(..., description="角色ID列表")
    is_active: Optional[bool] = Field(None, description="是否激活")


class RoleQueryParams(BaseModel):
    """角色查询参数模型"""
    name: Optional[str] = Field(None, description="角色名称")
    code: Optional[str] = Field(None, description="角色编码")
    is_active: Optional[bool] = Field(None, description="是否激活")
    is_system: Optional[bool] = Field(None, description="是否系统角色")


class RoleUserInfo(BaseModel):
    """角色用户信息模型"""
    id: int = Field(description="用户ID")
    username: str = Field(description="用户名")
    nickname: Optional[str] = Field(None, description="昵称")
    email: Optional[str] = Field(None, description="邮箱")
    is_active: bool = Field(description="是否激活")
    created_at: datetime = Field(description="创建时间")

    class Config:
        from_attributes = True


class RoleUsersResponse(BaseModel):
    """角色用户列表响应模型"""
    total: int = Field(description="总数")
    items: List[RoleUserInfo] = Field(description="用户列表")
